import { Http,Response } from '@angular/http';
import { Injectable } from '@angular/core';
import { Observable} from 'rxjs/observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
/*
  Generated class for the RestProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class RestProvider {
  private weatherApi="http://apicloud.mob.com/v1/weather/query"
  constructor(public http: Http) {
    // console.log('Hello RestProvider Provider');
  }
  weather(city,province){
    return this.getUrlReturn(this.weatherApi+`?key=1e81b0eb3edb0&city=${city}&province=${province}`)
  }
  private getUrlReturn(url:string):Observable<string[]>{
    return this.http.get(url).map(this.extractData).catch(this.handleError);
  }
  private extractData(res:Response){
    let body:any=res.json();
    // return JSON.parse(body)||{};
    return body||{};
  }
  private handleError(error:Response|any){
    let errMsg:string;
    if(error instanceof Response){
      const body:any=error.json()||'';
      const err=body.error||JSON.stringify(body);
      errMsg=`${err}`;
    }else{
      errMsg=error.message?error.message:error.toString();
    }
   console.error(errMsg);
    return Observable.throw(errMsg);
    
  }
}
